/*
 * @Description:
 * @Author: zhaokun
 * @Date: 2022-01-25 10:16:20
 * @LastEditTime: 2022-01-28 08:12:24
 * @FilePath: \user\rpc\internal\svc\servicecontext.go
 */
package svc

import (
	"time"
	"user/common"
	"user/rpc/internal/config"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/tal-tech/go-zero/core/logx"
	"github.com/tal-tech/go-zero/core/service"
	"xorm.io/core"
)

type ServiceContext struct {
	Config config.Config
	Model  *xorm.Engine
	Cache  common.CacheUtil
}

func NewServiceContext(c config.Config) *ServiceContext {
	var engine *xorm.Engine
	var err error
	switch c.DbEngine.Type {
	case "mysql":
		engine, err = xorm.NewEngine("mysql", c.Mysql.DataSource)
	default:
		engine, err = xorm.NewEngine("mysql", c.Mysql.DataSource)

	}

	if err != nil {
		logx.Error("DbError:", err.Error())
	}

	if c.Mode == service.TestMode || c.Mode == service.DevMode {
		engine.ShowSQL(true)
	}

	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "nw_")
	engine.SetTableMapper(tbMapper)
	//开启Db缓存
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	engine.SetDefaultCacher(cacher)
	//设置连接池
	engine.SetMaxIdleConns(c.DbEngine.IdleConns)
	engine.SetMaxOpenConns(c.DbEngine.OpenConns)
	engine.SetConnMaxLifetime(time.Duration(c.DbEngine.Lifetime))
	cacheConf := &common.RedisConf{}
	cacheUtil := common.NewNwCacheUtil(cacheConf)
	return &ServiceContext{
		Config: c,
		Model:  engine,
		Cache:  cacheUtil,
	}
}
